<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            function TreeNode(val, left, right) {
                this.val = val === undefined ? 0 : val
                this.left = left === undefined ? null : left
                this.right = right === undefined ? null : right
            }
            /* 
      使用栈的方式，先将根节点入栈，然后出栈，再将右孩子入栈，再加入左孩子。
      但是这种迭代法用的不多，大部分还是使用的递归法
      */
            let tree = {
                val: 1,
                left: {
                    val: 2,
                    left: {
                        val: 4,
                    },
                },
                right: {
                    val: 3,
                    right: {
                        val: 5,
                    },
                },
            }
            function preOrder(root) {
                let stack = []
                let result = []
                if (!root) return
                stack.push(root)
                while (stack.length) {
                    let node = stack.pop()
                    result.push(node.val)
                    if (node.right) {
                        stack.push(node.right)
                    }
                    if (node.left) {
                        stack.push(node.left)
                    }
                }
                return result
            }
            console.log(preOrder(tree))
        </script>
    </body>
</html>
